package com.zwj.hmall.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import org.springframework.transaction.support.TransactionTemplate;

/**
 * @author 张文接
 * @version 1.0
 * @createTime 2024/8/4 13:38
 */
@Service
public class TransferService {
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private PlatformTransactionManager transactionManager;
    @Autowired
    private TransactionTemplate transactionTemplate;

    public void transfer() {
        DefaultTransactionDefinition definition = new DefaultTransactionDefinition();
        TransactionStatus status = transactionManager.getTransaction(definition);
        try {
            jdbcTemplate.update("update tb_user set money = money + ? where account = ?", 1, "mike");
            int i = 1 / 0;
            //提交事务
            transactionManager.commit(status);
        } catch (DataAccessException e) {
            e.printStackTrace();
            //回滚事务
            transactionManager.rollback(status);
        }
    }

    public void test(){
        System.out.println("test success");
    }
}
